package com.itheima.gateway.filters;

import com.itheima.gateway.config.AuthProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.RequestPath;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.lang.annotation.Annotation;

//@Component
public class AuthGlobalFilter implements GlobalFilter, Order {
    @Autowired
    private AuthProperties authProperties;

    private AntPathMatcher antPathMatcher = new AntPathMatcher();
    @Override
    public Class<? extends Annotation> annotationType() {
        return null;
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        HttpHeaders headers = request.getHeaders();
        String string = request.getPath().toString();
        String token = headers.getFirst("token");
        System.out.println("gateway获取user-info:"+headers.get("user-info"));

        //路径为/user开头的直接放行，其他的要检查token
        for (String excludePath : authProperties.getExcludePaths()) {
            System.out.println(excludePath);
            if (antPathMatcher.match(excludePath, string)) {
                return chain.filter(exchange);
            }
        }
        if (token == null || token.isEmpty()) {
            ServerHttpResponse response = exchange.getResponse();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        ServerWebExchange build = exchange.mutate().request(builder -> builder.header("userId", "1164")).build();
        return chain.filter(build);
    }

    @Override
    public int value() {
        return 0;
    }
}
